<!DOCTYPE html>
<html>
  <head lang="zh">
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="renderer" content="webkit" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1,user-scalable=0"
    />
    <title>Luckysheet</title>

    <link rel="stylesheet" href="./plugins/css/pluginsCss.css" />
    <link rel="stylesheet" href="./plugins/plugins.css" />
    <link rel="stylesheet" href="./css/luckysheet.css" />
    <link rel="stylesheet" href="./assets/iconfont/iconfont.css" />
    <script src="./plugins/js/plugin.js"></script>

    <!-- rollup luckysheet.js -->
    <script src="./luckysheet.umd.js"></script>
  </head>

  <body>
    <div
      id="luckysheet"
      style="
        margin: 0px;
        padding: 0px;
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0px;
        top: 0px;
      "
    ></div>
    <script>
      let copyDataSourceList = [];
      function isJSON(value) {
        try {
          JSON.parse(value);
          return true;
        } catch (e) {
          return false;
        }
      }
      function setValue(
        luckysheet,
        dataDetailList,
        dataSourceList,
        productObj
      ) {
        // 设置产品信息 item.cellPosition
        dataSourceList.forEach((item) => {
          if ([2, 3].includes(item.writeDataSourceType)) {
            let arr = item.cellPosition.split(",");
            luckysheet.setCellValue(arr[0] * 1, arr[1] * 1, item.dataVal);
          }
        });
        for (let i = 0; i < dataDetailList.length; i++) {
          let pA = dataDetailList[i].cellPosition.split(",");
          let v = dataDetailList[i].content;
          if (v && isJSON(v) && JSON.parse(v)?.url) {
            let obj = JSON.parse(v) || {};
            luckysheet.insertImage(obj.url, {
              ...obj,
              w: Math.floor(obj.w / obj.zoomRatio),
              h: Math.floor(obj.h / obj.zoomRatio),
            });
            let signUrlMap = luckysheet.getStore("signUrlMap");
            signUrlMap[`${obj.rowIndex},${obj.colIndex}`] = obj;
            luckysheet.setStore("signUrlMap", signUrlMap);
            v = "电子签名";
          }
          luckysheet.setCellValue(pA[0] * 1, pA[1] * 1, v);
        }
        luckysheet.workbookCreateAfter();
      }
      function setCache(luckysheet, editableRegion, cache) {
        let cells = [];
        editableRegion.forEach((item) => {
          // 字符串转数组区域
          let range = luckysheet.getRangeByTxt(item);
          // 数组区域转 单元格数组
          cells.push(...luckysheet.getRangeWithFlatten([range]));
        });
        for (let i = 0; i < cells.length; i++) {
          let { r, c } = cells[i];
          let obj = cache.find((v) => {
            return v.cellPosition == r + "," + c;
          });
          if (obj) {
            luckysheet.setCellValue(r, c, obj.content);
          }
        }
      }

      // 初始化
      function initModel({ modelData, userList, roleList }) {
        let { name, jsonData, dataSourceList, drawSettingList } =
          JSON.parse(modelData);
        let permissionList = cellPos(dataSourceList);
        copyDataSourceList = dataSourceList;
        let options = {
          container: "luckysheet",
          showsheetbar: false, // 隐藏左下角
          title: name,
          forceCalculation: false,
          plugins: ["chart"],
          data: [
            jsonData
              ? JSON.parse(jsonData)
              : {
                  name: "default",
                },
          ],
          functionButton: `
      		<button id="luckysheet-share-btn-title" class="btn btn-primary" style="margin:0 5px;">保存</button>
      		`,
        };
        luckysheet.create({
          setting: options,
          userList: JSON.parse(userList || "[]"),
          roleList: JSON.parse(roleList || "[]"),
          permissionList,
          drawSettingList: drawSettingList,
          dataSourceList: dataSourceList.map((item) => {
            return {
              cellPosition: item.cellPosition,
              writeDataSourceId: item.writeDataSourceId,
              writeDataSourceName: "",
              writeDataSourceType: item.writeDataSourceType,
              requre: item.requre,
              pname: item.pname,
              did: item.did,
              oid: item.oid,
              writeDataSourceName: item.writeDataSource
                ? item.writeDataSource.name
                : "无配置",
            };
          }),
        });
        sessionStorage.removeItem("sessionDataSourceList");
      }
      function initDataEntry({ modelData, data, cache }) {
        let { name, jsonData, dataSourceList, productName, productType } =
          JSON.parse(modelData);
        let { dataDetailList, rejectionRange, productCode, id } =
          JSON.parse(data);
        let permissionList = cellPos(dataSourceList);
        copyDataSourceList = dataSourceList;
        let functionButton = `
        <button id="luckysheet-share-btn-title-get-value" class="btn btn-primary m-r-10">取值</button>
        <button id="luckysheet-share-btn-title-data" class="btn btn-primary m-r-10" >保存</button>
        `;
        let options = {
          container: "luckysheet",
          showsheetbar: false, // 隐藏左下角
          showtoolbar: false, //是否第二列显示工具栏
          title: name,
          forceCalculation: false,
          plugins: ["chart"],
          data: [
            jsonData
              ? JSON.parse(jsonData)
              : {
                  name: "default",
                },
          ],
          cellRightClickConfig: {
            copy: false, // copy
            copyAs: false, // copy as
            paste: false, // paste
            insertRow: false, // insert row
            insertColumn: false, // insert column
            deleteRow: false, // delete the selected row
            deleteColumn: false, // delete the selected column
            deleteCell: false, // delete cell
            hideRow: false, // hide the selected row and display the selected row
            hideColumn: false, // hide the selected column and display the selected column
            rowHeight: false, // row height
            columnWidth: false, // column width
            clear: false, // clear content
            matrix: false, // matrix operation selection
            sort: false, // sort selection
            filter: false, // filter selection
            chart: false, // chart generation
            image: false, // insert picture
            link: false, // insert link
            data: false, // data verification
            cellFormat: false, // Set cell format
            setPermissions: false, //miaoks
            specialMark: false,
            getData: false,
            dataOrigin: false,
          },
          allowEdit: false,
          allowCopy: false,
          functionButton: functionButton,
          hook: {
            cellMousedown: cellMousedown, //绑定鼠标事件
            imageDeleteAfter: imageDeleteAfter, //绑定鼠标事件
          },
        };

        // 可编辑区域
        let editableRegion = [];
        // 不可查看区域
        let unviewableRegion = [];
        permissionList &&
          permissionList.forEach((item) => {
            if (
              item.cellRange &&
              item.permissionSettingDetailList[0] &&
              item.permissionSettingDetailList[0].operationAuthority == 1
            ) {
              editableRegion.push(...item.cellRange.split(","));
            } else if (
              item.cellRange &&
              item.permissionSettingDetailList[0] &&
              item.permissionSettingDetailList[0].operationAuthority == 2
            ) {
              unviewableRegion.push(...item.cellRange.split(","));
            }
          });

        luckysheet.create({
          setting: options,
          editableRegion: editableRegion.join(","),
          unviewableRegion: unviewableRegion.join(","),
          dataSourceList,

          product: {
            productName,
            productType,
            productCode,
          },
        });
        luckysheet.setStore("saveRatio", JSON.parse(jsonData).zoomRatio);
        // 设置已录入数据
        setTimeout(() => {
          let ch = JSON.parse(cache);
          setCache(luckysheet, editableRegion, ch);
          setValue(luckysheet, dataDetailList, dataSourceList, {
            3: productType,
            4: productName,
            5: productCode,
          });
        }, 500);

        // 设置驳回区样式
        if (rejectionRange) {
          let rejectionRangeArr = JSON.parse(rejectionRange);
          rejectionRangeArr.forEach((item) => {
            let arr = item.split(",");

            // 设置可编辑单元格边框
            luckysheet.setCellFormat(arr[0], arr[1], "bd", {
              style: "1",
              color: "#FF0000",
            });
            // 设置可编辑单元格背景颜色
            luckysheet.setCellFormat(arr[0], arr[1], "fc", "#FF0000");
          });
        }
      }
      function initviewOnly({ modelData, data, roleList }, command) {
        let { name, jsonData, dataSourceList, productName, productType } =
          JSON.parse(modelData);
        let { dataDetailList, productCode } = JSON.parse(data);
        let permissionList = cellPos(dataSourceList) || [];
        let jsData = {
          name: "default",
        };
        if (jsonData) {
          jsData = JSON.parse(jsonData);
          jsData.config["authority"] = {
            password: "",
            algorithmName: "None",
            saltValue: null,
            hintText: "",
            sheet: 1,
            selectLockedCells: 1,
            selectunLockedCells: 1,
            formatCells: 0,
            formatColumns: 0,
            formatRows: 0,
            insertColumns: 0,
            insertRows: 0,
            insertHyperlinks: 0,
            deleteColumns: 0,
            deleteRows: 0,
            sort: 0,
            filter: 0,
            usePivotTablereports: 0,
            editObjects: 0,
            editScenarios: 0,
            allowRangeList: [],
          };
        }
        let printBtn = "";
        if (window.innerWidth > 1000) {
          printBtn =
            '<button id="luckysheet-print-btn" class="btn btn-primary" >选区打印</button>';
        }
        let options = {
          container: "luckysheet",
          showsheetbar: false, // 隐藏左下角
          showtoolbar: false, //是否第二列显示工具栏
          title: name,
          forceCalculation: false,
          plugins: ["chart"],
          data: [jsData],
          allowEdit: false,
          allowCopy: false,
          cellRightClickConfig: {
            copy: false, // copy
            copyAs: false, // copy as
            paste: false, // paste
            insertRow: false, // insert row
            insertColumn: false, // insert column
            deleteRow: false, // delete the selected row
            deleteColumn: false, // delete the selected column
            deleteCell: false, // delete cell
            hideRow: false, // hide the selected row and display the selected row
            hideColumn: false, // hide the selected column and display the selected column
            rowHeight: false, // row height
            columnWidth: false, // column width
            clear: false, // clear content
            matrix: false, // matrix operation selection
            sort: false, // sort selection
            filter: false, // filter selection
            chart: false, // chart generation
            image: false, // insert picture
            link: false, // insert link
            data: false, // data verification
            cellFormat: false, // Set cell format
            setPermissions: false, //miaoks
            specialMark: false,
            getData: false,
            dataOrigin: false,
          },
          functionButton: printBtn,
        };
        // 可编辑区域
        let editableRegion = [];
        // 不可查看区域
        let unviewableRegion = [];
        permissionList.forEach((item) => {
          if (
            item.cellRange &&
            item.permissionSettingDetailList[0] &&
            item.permissionSettingDetailList[0].operationAuthority == 2
          ) {
            unviewableRegion.push(...item.cellRange.split(","));
          } else if (
            item.cellRange &&
            item.permissionSettingDetailList[0] &&
            item.permissionSettingDetailList[0].operationAuthority == 1
          ) {
            editableRegion.push(...item.cellRange.split(","));
          }
        });
        luckysheet.create({
          setting: options,
          editableRegion: editableRegion.join(","),
          unviewableRegion: unviewableRegion.join(","),
          roleList: JSON.parse(roleList || "[]"),
          isViewOnly: true,
        });
        luckysheet.setStore("saveRatio", JSON.parse(jsonData).zoomRatio);
        // 设置已录入数据
        setTimeout(() => {
          setValue(luckysheet, dataDetailList, dataSourceList, {
            3: productType,
            4: productName,
            5: productCode,
          });
        }, 500);
        setTimeout(() => {
          luckysheet.setStore("editableRegion", []);
        }, 1000);
      }

      function initRejectView({ modelData, data }) {
        let {
          modelName,
          modelDataJson,
          dataSources,
          productName,
          productType,
          rejectionRange,
        } = JSON.parse(modelData);
        let { dataDetailList, productCode } = JSON.parse(data);
        let permissionList = cellPos(dataSourceList);
        let options = {
          container: "luckysheet",
          showsheetbar: false, // 隐藏左下角
          showtoolbar: false, //是否第二列显示工具栏
          title: modelName,
          forceCalculation: false,
          plugins: ["chart"],
          data: [
            modelDataJson
              ? JSON.parse(modelDataJson)
              : {
                  name: "default",
                },
          ],
          allowEdit: false,
          allowCopy: false,
        };
        // 不可查看区域
        let unviewableRegion = [];
        permissionList &&
          permissionList.forEach((item) => {
            if (
              item.cellRange &&
              item.permissionSettingDetailList[0] &&
              item.permissionSettingDetailList[0].operationAuthority == 2
            ) {
              unviewableRegion.push(...item.cellRange.split(","));
            }
          });
        luckysheet.create({
          setting: options,
          unviewableRegion: unviewableRegion.join(","),
        });
        // 设置驳回区样式
        if (rejectionRange) {
          let rejectionRangeArr = JSON.parse(rejectionRange);
          rejectionRangeArr.forEach((item) => {
            let arr = item.split(",");

            // 设置可编辑单元格边框
            luckysheet.setCellFormat(arr[0], arr[1], "bd", {
              style: "1",
              color: "#FF0000",
            });

            // 设置可编辑单元格背景颜色
            luckysheet.setCellFormat(arr[0], arr[1], "fc", "#FF0000");
          });
        }
        // 设置已录入数据
        setTimeout(() => {
          setValue(luckysheet, dataDetailList, dataSources, {
            3: productType,
            4: productName,
            5: productCode,
          });
        }, 500);
      }
      //单元格数字转字母
      function cellPos(list) {
        let rangeAxis = [];
        list.forEach((cell) => {
          if ([1, 2, 3].includes(cell.writeDataSourceType)) {
            let c = Number(cell.cellPosition.split(",")[1]);
            let r = Number(cell.cellPosition.split(",")[0]);
            let ordA = "A".charCodeAt(0);
            let ordZ = "Z".charCodeAt(0);
            let len = ordZ - ordA + 1;
            let s = "";
            while (c >= 0) {
              s = String.fromCharCode((c % len) + ordA) + s;
              c = Math.floor(c / len) - 1;
            }
            rangeAxis.push(s + (r + 1));
          }
        });
        return [
          {
            cellRange: rangeAxis.join(","),
            name: "",
            roleIds: "",
            permissionSettingDetailList: [{ operationAuthority: 1 }],
          },
        ];
      }
      function imageDeleteAfter(imageItem) {
        let url = imageItem.src;
        let signUrlMap = luckysheet.getStore("signUrlMap");
        for (const key in signUrlMap) {
          if (Object.hasOwnProperty.call(signUrlMap, key)) {
            const element = signUrlMap[key];
            if (element.url == url) {
              delete signUrlMap[`${element.rowIndex},${element.colIndex}`];
            }
          }
        }
        luckysheet.setStore("signUrlMap", signUrlMap);
      }
      function cellMousedown(cell, position, sheetFile, ctx) {
        var r = position.r;
        var c = position.c;
        let signUrlMap = luckysheet.getStore("signUrlMap");
        if (!signUrlMap[`${r},${c}`]) {
          window.parent.postMessage(
            {
              command: "setSign",
              position: position,
              dataSourceList: JSON.stringify(copyDataSourceList),
            },
            "*"
          );
        }
      }
      function setDataSourcestyle(dataSources) {
        dataSources.forEach((item) => {
          if (!item.writeDataSourceName) {
            let arr = item.cellPosition.split(",") || [,];
            // 设置来源单元格边框背景颜色

            if (item.writeDataSourceType == 5) {
              luckysheet.setCellFormat(arr[0], arr[1], "bd", {
                borderType: "border-none",
              });
              luckysheet.setCellValue(arr[0], arr[1], "");
              let resetBdArr = [];
              dataSources.forEach((pre) => {
                let t = arr[0] == "0" ? 0 : arr[0] - 1;
                let l = arr[1] == "0" ? 0 : arr[1] - 1;
                let r = arr[1] - 0 + 1;
                let b = arr[0] - 0 + 1;
                if (
                  pre.writeDataSourceType != 5 &&
                  pre.cellPosition == `${t},${arr[1]}`
                ) {
                  luckysheet.setCellFormat(t, arr[1], "bd", {
                    style: "1",
                    color: "#000000",
                  });
                }
                if (
                  pre.writeDataSourceType != 5 &&
                  pre.cellPosition == `${arr[0]},${l}`
                ) {
                  luckysheet.setCellFormat(arr[0], l, "bd", {
                    style: "1",
                    color: "#000000",
                  });
                }
                if (
                  pre.writeDataSourceType != 5 &&
                  pre.cellPosition == `${arr[0]},${r}`
                ) {
                  luckysheet.setCellFormat(arr[0], r, "bd", {
                    style: "1",
                    color: "#000000",
                  });
                }
                if (
                  pre.writeDataSourceType != 5 &&
                  pre.cellPosition == `${b},${arr[1]}`
                ) {
                  luckysheet.setCellFormat(b, arr[1], "bd", {
                    style: "1",
                    color: "#000000",
                  });
                }
              });
            } else {
              luckysheet.setCellFormat(arr[0], arr[1], "bd", {
                style: "1",
                color: "#000000",
              });
            }
            if (item.writeDataSourceType == 4) {
              luckysheet.setCellValue(arr[0], arr[1], "电子签名");
              luckysheet.setCellFormat(arr[0], arr[1], "vt", 0);
              luckysheet.setCellFormat(arr[0], arr[1], "ht", 0);
              luckysheet.setCellFormat(arr[0], arr[1], "fc", "#0188fb");
            }
            let bgColor =
              item.writeDataSourceType == 5
                ? "#fff"
                : item.requre
                ? "#E4D6A1"
                : "#dbdbdb";

            luckysheet.setCellFormat(arr[0], arr[1], "bg", bgColor);
          }
        });
      }

      window.addEventListener("message", (event) => {
        switch (event.data.command) {
          case "initModel":
            luckysheet.setStore("detailType", 1);
            initModel(event.data);
            break;
          case "dataEntry":
            luckysheet.setStore("detailType", 2);
            initDataEntry(event.data);
            break;
          case "getNewValueSucess":
            let newData = JSON.parse(event.data.data || "{dataSourceList:[]}");
            setTimeout(() => {
              setValue(luckysheet, [], newData.dataSourceList);
              luckysheet.hideStoreLoading();
            }, 500);
            break;
          case "viewOnly":
          case "audit":
          case "loading":
            luckysheet.showStoreLoading();
            break;
          case "print":
            luckysheet.setStore("detailType", 3);
            initviewOnly(event.data, event.data.command);
            break;
          case "getSingSucess":
            let { url, position } = JSON.parse(event.data.data || "{}");
            luckysheet.insertImage(url, {
              rowIndex: position.r,
              colIndex: position.c,
              w: position.end_c - position.start_c - 0.5,
              h: position.end_r - position.start_r - 0.5,
              zoomRatio:
                luckysheet.getStore("zoomRatio") /
                luckysheet.getStore("saveRatio"),
              success: setImageSuccess(url, position),
            });
            break;
          case "replyApi":
            let arr = event.data.cellPosition.split(",");
            let val = luckysheet.getCellValue(arr[0], arr[1]);
            if (event.data.ty) {
              luckysheet.setCellValue(
                arr[0],
                arr[1],
                JSON.parse(event.data.data)
              );
            } else {
              if (!val && val != 0) {
                luckysheet.setCellValue(
                  arr[0],
                  arr[1],
                  JSON.parse(event.data.data)
                );
              }
            }

            break;
          case "auditSucess":
            $("#luckysheet-audit-approved-btn").hide();
            $("#luckysheet-audit-rejection-btn").hide();
            break;
          case "saveDataSucess":
            $("#luckysheet-extract-data-tr-btn").hide();
            $("#luckysheet-share-btn-title-data").hide();
            $("#luckysheet-share-btn-title-cache").hide();
            $("#luckysheet-share-btn-title-get-value").hide();
            luckysheet.setStore("detailType", 3);
            luckysheet.exitEditMode();
            setTimeout(() => {
              luckysheet.setStore("editableRegion", []);
            }, 1000);
            break;
          case "rejectView":
            initRejectView(event.data);
            break;
          case "addPointSucess":
            sessionStorage.setItem(
              "sessionDataSourceList",
              JSON.stringify(JSON.parse(event.data.data).dataSourceList)
            );
            let dataSources = JSON.parse(event.data.data).dataSourceList;
            setDataSourcestyle(dataSources);
            break;
          default:
            break;
        }
      });
      function setImageSuccess(url, position) {
        let signUrlMap = luckysheet.getStore("signUrlMap");
        signUrlMap[`${position.r},${position.c}`] = {
          url,
          rowIndex: position.r,
          colIndex: position.c,
          w: position.end_c - position.start_c - 0.5,
          h: position.end_r - position.start_r - 0.5,
          zoomRatio:
            luckysheet.getStore("zoomRatio") / luckysheet.getStore("saveRatio"),
        };
        luckysheet.setStore("signUrlMap", signUrlMap);
        window.parent.postMessage(
          {
            command: "setImageSuccess",
          },
          "*"
        );
      }
    </script>
    <style>
      /* 自定义loading演示样式 */
      @keyframes loading-rotate {
        0% {
          transform: rotate(0deg);
        }

        100% {
          transform: rotate(360deg);
        }
      }

      @keyframes loading-dash {
        0% {
          stroke-dasharray: 1, 200;
          stroke-dashoffset: 0;
        }

        50% {
          stroke-dasharray: 90, 150;
          stroke-dashoffset: -40px;
        }

        100% {
          stroke-dasharray: 90, 150;
          stroke-dashoffset: -120px;
        }
      }

      .loadingAnimation {
        width: 3em;
        height: 3em;
        animation: loading-rotate 2s linear infinite;
      }

      .loadingAnimation circle {
        animation: loading-dash 1.5s ease-in-out infinite;
        stroke-dasharray: 90, 150;
        stroke-dashoffset: 0;
        stroke-width: 2;
        stroke: currentColor;
        stroke-linecap: round;
      }
    </style>
  </body>
</html>
